package com.hk.blog.service.impl;

import com.hk.blog.domain.UserRole;
import com.hk.blog.repository.jpa.UserRoleRepository;
import com.hk.blog.service.UserRoleService;
import com.hk.blog.vo.UserRoleBean;
import com.hk.commons.util.CollectionUtils;
import com.hk.core.data.jpa.repository.BaseJpaRepository;
import com.hk.core.service.jpa.impl.JpaServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Kevin
 * @date 2022-07-02 20:46
 */
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends JpaServiceImpl<UserRole, Long>
        implements UserRoleService {

    private final UserRoleRepository userRoleRepository;

    @Override
    protected BaseJpaRepository<UserRole, Long> getBaseRepository() {
        return userRoleRepository;
    }

    @Override
    @Transactional
    public void updateRole(UserRoleBean body) {
        userRoleRepository.deleteByUserId(body.getUserId());
        if (CollectionUtils.isNotEmpty(body.getRoleIds())) {
            List<UserRole> list = body.getRoleIds().stream()
                    .map(roleId -> new UserRole().setUserId(body.getUserId()).setRoleId(roleId))
                    .collect(Collectors.toList());
            userRoleRepository.saveAll(list);
        }
    }

    @Override
    public Set<Long> findRoleIdByUserId(Long userId) {
        return userRoleRepository.findRoleIdByUserId(userId);
    }


}
